package com.lianniu.web.login.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.lianniu.redis.RedisUtils;



public class CheckLoginFilter implements Filter {
  private final static Logger logger = Logger.getLogger(CheckLoginFilter.class);

  public void init(FilterConfig filterConfig) throws ServletException {}

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    String url = req.getRequestURI().toString();
    logger.info("CheckLoginFilter doFilter url:" + url);

    if (contains(CheckUrl.NO_CHECK_ACCESS_URLS, url)) {
      chain.doFilter(request, response);
      return;
    }

    String token = (String) req.getHeader("token");
    logger.info("CheckLoginFilter doFilter token:" + token);
    RedisUtils redisUtils = new RedisUtils();


    if (!(token == null || "".equals(token.trim()))
        && redisUtils.hashExists("lianniuSaasToken", token)) {
      chain.doFilter(request, response);
      return;
    }
    req.getRequestDispatcher("/rest/userCheckFail.do").forward(request, response);

  }

  public void destroy() {}

  /**
   * �ж�ĳ���ַ��Ƿ������������
   * 
   * @param stringArray ԭ����
   * @param source ���ҵ��ַ�
   * @return �Ƿ��ҵ�
   */
  public static boolean contains(String[] stringArray, String source) {
    List<String> tempList = Arrays.asList(stringArray);
    // ����list�İ��,�����ж�
    if (tempList.contains(source)) {
      return true;
    } else {
      return false;
    }
  }


}
